package cn.sunxyz.core.bean;

import cn.sunxyz.common.utils.reflect.ClassUtil;
import cn.sunxyz.common.utils.reflect.ReflectionUtil;
import cn.sunxyz.core.bean.annotation.Plugins;
import cn.sunxyz.core.bean.plugin.AbstractPlugin;
import cn.sunxyz.core.bean.plugin.Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2017/5/22.
 */
class PluginsManger {

    private static final Logger logger = LoggerFactory.getLogger(PluginsManger.class);

    private static final Map<String, Class<?>> REGISTER_MAP = new HashMap<>();
    private static final String PROPERTIES_NAME = "bloom.properties";
    private static final transient List<String> REGISTER_LIST = new LinkedList<>();

    /**
     * 初始化插件
     */
    static List<Plugin> initPlugins(ClassContainer classContainer) {
        List<Class<?>> pluginsCollection = classContainer.listClassByAnnotation(Plugins.class);
        registerProperPlugins();//注册系统提供插件
        for (Class<?> pluginsClazz : pluginsCollection) {
            Plugins plugins = pluginsClazz.getAnnotation(Plugins.class);
            Class<? extends Plugin>[] pluginClsArray = plugins.value();
            for (Class<? extends Plugin> pluginCls : pluginClsArray) {
                Class<?> superCls = pluginCls.getSuperclass();
                //下面情况不允许覆盖
                if (!(superCls.equals(Object.class) || superCls.equals(AbstractPlugin.class))) {//此处默认如果 覆盖某一插件 extends 该插件
                    logger.debug("[plugin cover] :=>  plugin {} cover {}", pluginCls.getName(), superCls.getName());
                    register(superCls.getName(), pluginCls);
                } else {
                    register(pluginCls);
                }
            }
        }
        return listPlugins();//根据注册顺序获取插件列表
    }

    //后注册的插件覆盖前面的插件
    private static void registerProperPlugins() {
        InputStream in = ClassLoader.getSystemResourceAsStream(PROPERTIES_NAME);
        Properties p = new Properties();
        try {
            p.load(in);
            p.forEach((clsKey, cls) -> {
                String className = clsKey.toString();
                String clsPath = cls.toString();
                if (ClassUtil.isPresent(clsPath)) {
                    register(className, ClassUtil.loadClass(clsPath));
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //注册插件 用户插件覆盖系统插件
    private static boolean register(String className, Class<?> cls) {
        if (REGISTER_MAP.containsKey(className)) {
            REGISTER_MAP.put(className, cls);
            return true;
        } else {
            REGISTER_LIST.add(className);//注册该插件
            REGISTER_MAP.put(className, cls);
            return false;
        }
    }

    private static boolean register(Class<?> cls) {
        return register(cls.getName(), cls);
    }

    private static List<Plugin> listPlugins() {
        return REGISTER_LIST.stream().map(className -> REGISTER_MAP.get(className)).map(ReflectionUtil::invokeConstructor).map(o -> (Plugin) o).collect(Collectors.toList());
    }
}
